//
//  MemoWriteViewController.m
//  MokoAPP
//
//  Created by 현식 강 on 11. 8. 14..
//  Copyright 2011 아이온. All rights reserved.
//

#import "MemoWriteViewController.h"
#import "MokoAppDelegate.h"
#import "ParsingDirector.h"
#import <QuartzCore/QuartzCore.h>

@implementation MemoWriteViewController
@synthesize toUserId, toTextField, toUserName;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWasShown:)
                                                     name:UIKeyboardDidShowNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    ((UIScrollView*)self.view).contentInset = contentInsets;
    ((UIScrollView*)self.view).scrollIndicatorInsets = contentInsets;
    
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    [((UIScrollView*)self.view) setContentSize:CGSizeMake(aRect.size.width, aRect.size.height + kbSize.height)];
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
        CGRect aRect = self.view.frame;
        aRect.size.height -= kbSize.height;
        [((UIScrollView*)self.view) setContentSize:CGSizeMake(aRect.size.width, aRect.size.height + kbSize.height)];
        if (activeView != nil && !CGRectContainsRect(aRect, activeView.frame) ) {
            CGPoint scrollPoint = CGPointMake(0.0, activeView.frame.origin.y+activeView.frame.size.height-kbSize.height - 50);
            [((UIScrollView*)self.view) setContentOffset:scrollPoint animated:YES];
        }
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    ((UIScrollView*)self.view).contentInset = contentInsets;
    ((UIScrollView*)self.view).scrollIndicatorInsets = contentInsets;
    [((UIScrollView*)self.view) setContentSize:memoWriteView.frame.size];
}
-(void)textViewDidBeginEditing:(UITextView *)textView {
    activeView = textView;
}
-(void)textViewDidEndEditing:(UITextView *)textView {
    activeView = nil;
}

- (void)dealloc
{
    [toUserName release];
    toUserName = nil;
    [toUserId release];
    toUserId = nil;
    [toTextField release];
    toTextField = nil;
    [titleTextField release];
    titleTextField = nil;
    [sendMemoButton release];
    sendMemoButton = nil;
    [contentTextView release];
    contentTextView = nil;
    [memoWriteView release];
    memoWriteView = nil;
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [toTextField setText:toUserName];
    contentTextView.placeholder = @"쪽지 내용을 입력하세요.";
    contentTextView.layer.cornerRadius = 7;
    contentTextView.clipsToBounds = YES;
    contentTextView.delegate = self;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if( alertView.tag == 500 ) {
        [self dismissModalViewControllerAnimated:YES];
    }
}

- (void)viewDidUnload
{
    [memoWriteView release];
    memoWriteView = nil;
    [toTextField release];
    toTextField = nil;
    [titleTextField release];
    titleTextField = nil;
    [sendMemoButton release];
    sendMemoButton = nil;
    [contentTextView release];
    contentTextView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)hideKeyboard:(id)sender {
    NSArray* subviews = [memoWriteView subviews];
    for( UIView* views in subviews ) 
        [views resignFirstResponder];
}

- (IBAction)sendMemo:(id)sender {
    GET_APPDELEGATE;
    NSString* addr = [NSString stringWithFormat:@"%@/zboard4/send_message.php", delegate.configVO.siteHostAddress];
    if( [titleTextField.text length] == 0 ) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"등록 불가" message:@"제목은 필수사항입니다." delegate:self cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [titleTextField becomeFirstResponder];
        [alert show];
        [alert release];
        return;
    }
    if( [contentTextView.text length] == 0 ) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"등록 불가" message:@"내용은 필수사항입니다." delegate:self cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [contentTextView becomeFirstResponder];
        [alert show];
        [alert release];
        return;
    }
    NSString* postBody = [NSString stringWithFormat:@"subject=%@&memo=%@&member_no=%@&kind=1", titleTextField.text, [contentTextView.text stringByReplacingOccurrencesOfString:@"\n" withString:@"\r\n"], toUserId];
    [delegate.httpClient requestURL:addr httpMethod:@"POST" bodyData:[postBody dataUsingEncoding:EUC_KR ] isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
}

-(void)finishLoading:(NSData *)data {
    ParsingDirector* director = [ParsingDirector sharedParsingDirector];
    director.responseData = data;
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"전송 완료" message:@"쪽지 전송이 완료 되었습니다." delegate:self cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
    if( [director getMemoWriteResult] ) {
        alert.tag = 500;
    } else {
        alert.title = @"전송 실패";
        alert.message = @"전송이 실패 하였습니다. 시코가 정상적으로 서비스 되고 있는지 확인 바랍니다.";
    }
    [alert show];
    [alert release];
}

- (IBAction)cancelMemo:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}
@end
